﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace Wawawum.RecycleBinCleaner
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void ProcessClean()
        {
            Cleaner.Clean(txBoxSiteUrl.Text);
        }

        private void btClean_Click(object sender, EventArgs e)
        {
            lbMessage.Visible = false;

            bool valid = ValidateChildren();

            if(valid)
            {
                DialogResult dr = MessageBox.Show(
                    "Etes-vous sur de vouloir vider la corbeille?",
                    "Confirmation",
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);

                if(dr == DialogResult.OK)
                {
                    progBar.Visible = true;
                    bckGrdWorkerCleaner.RunWorkerAsync();
                }
            }
        }

        private void txBoxSiteUrl_Validating(object sender, CancelEventArgs e)
        {
            // Validation du format de l'URL

            string url = txBoxSiteUrl.Text;
            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                e.Cancel = true;
                lbMessage.Text = "URL invalide";
                lbMessage.Visible = true;
            }
            else if(!Cleaner.SiteUrlIsValid(url))
            {
                e.Cancel = true;
                lbMessage.Text = "Site introuvable";
                lbMessage.Visible = true;
            }
            else
            {
                e.Cancel = false;
                lbMessage.Visible = false;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = false; // Autorise l'utilisateur a fermer la fenêtre même si la validation est incorrecte
        }

        private void bckGrdWorkerCleaner_DoWork(object sender, DoWorkEventArgs e)
        {
            ProcessClean();
        }

        private void bckGrdWorkerCleaner_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progBar.Visible = false;

            if(e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if(e.Cancelled)
            {
                MessageBox.Show("Une erreur inconnue s'est produite", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Nettoyage terminé");
            }
        }
    }
}
